package io.terminus.lego.shinda.web.oauth2.client.token

import io.terminus.lego.shinda.web.oauth2.client.converter.MultityUserAuthenticationConverter
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.annotation.Bean
import org.springframework.core.io.ClassPathResource
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory
import org.springframework.stereotype.Component
import org.springframework.util.FileCopyUtils


/**
 * @author wangmeng
 * @date 2018/4/13
 */
@Component
open class JWTTokenStoreConfig {

    /**
     * 这个是JWT转换器，将Authentication、AccessToken转换成JWT协议信息，实际上只有一层Map<->jwt的转换功能
     *
     */
    @Bean
    fun jwtConverter(): JwtAccessTokenConverter {
        val convert = JwtAccessTokenConverter()
        val publicKey = String(FileCopyUtils.copyToByteArray(ClassPathResource("rsa/rsa.crt").inputStream))
        val keyStoreKeyFactory = KeyStoreKeyFactory(ClassPathResource("rsa/private.jks"), "terminus.io".toCharArray())
        convert.setVerifierKey(publicKey)
        convert.setKeyPair(keyStoreKeyFactory.getKeyPair("terminus"))
        /**
         * 注意是他做的哦
         * 将AccessToken、Authentication转成Map
         * 从Map提取AccessToken、Authentication信息
         */
        val tokenConverter = DefaultAccessTokenConverter()
        tokenConverter.setUserTokenConverter(MultityUserAuthenticationConverter())
        convert.accessTokenConverter=tokenConverter

        convert.afterPropertiesSet()
        return convert
    }

    @Bean
    fun jwtTokenStore(
            @Qualifier("jwtConverter")
            convert:JwtAccessTokenConverter): JwtTokenStore {
        return JwtTokenStore(convert)
    }
}
